//
//  LBSTableViewController.m
//  WildDonkey
//
//  Created by 佟小波 on 15/3/27.
//  Copyright (c) 2015年 lanou. All rights reserved.
//

#import "LBSTableViewController.h"
#import "NearbyTableViewCell.h"
#import "GoogleToBaidu.h"
#import "AFNetworking.h"
#import "TravelDetail.h"
#import "NearbyData.h"
#import "TravelImpressionController.h"


@interface LBSTableViewController ()
{
	CLLocationManager *locationManager;//本地的地理位置信息
	CLGeocoder *geocoder;//坐标转换为地址
	CLPlacemark *placemark;//地址标记
}
//菊花
@property (nonatomic,retain) UIActivityIndicatorView *activityIndicator;

@property (nonatomic,retain) NSMutableArray *array;
@property (nonatomic,retain) NSDictionary *dic;
@property (nonatomic,retain) NearbyData *nearbyData;


@end

@implementation LBSTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
	[self beginLBS];
	

	
	//线程控制 废弃
	/*	//线程序列
	 dispatch_queue_t queue = dispatch_queue_create("xx", DISPATCH_QUEUE_SERIAL);
	 dispatch_async(queue, ^{
		NSLog(@"开始定位");
		
	 
	 });
	 
	 dispatch_async(queue, ^{
		//[self loadData];
		dispatch_async(dispatch_get_main_queue(), ^{
	 NSLog(@"address %@",self.address);
	 
		});
	 });
	 */
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

//图片加载菊花
- (void)loading
{
	_activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleWhiteLarge)];
	self.activityIndicator.frame = CGRectMake(self.view.center.x - 20, self.view.center.y - 40, 30, 30) ;
	self.activityIndicator.center = CGPointMake(self.view.center.x, self.view.center.y - 30);
	self.activityIndicator.color = [UIColor grayColor];
	[self.view addSubview:self.activityIndicator];
	[self.activityIndicator startAnimating];
	
	
}

//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
//{
//	
//}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section
{
	if (1 == section ) {
		return 30	;
	}else{
		return 0;
	}
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return 20;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return 100;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	self.nearbyData = nil;
	if (indexPath.row < [self.array count]) {
		self.nearbyData = self.array[indexPath.row];
	}
	
	
	
	static NSString *cellIdentifier = @"reuseIdentifier";
	NearbyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier ];
    // Configure the cell...
	if (nil == cell) {
		cell = [[NearbyTableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:cellIdentifier];
	}
	
	cell.data = self.nearbyData;
	
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	
	TravelImpressionController *traveVC = [[TravelImpressionController alloc] initWithStyle:(UITableViewStyleGrouped)];
	
#pragma mark error
	
	if (indexPath.row < [self.array count]) {
		traveVC.detail = self.array[indexPath.row];
	}
	//	NearbyData *data = [[NearbyData alloc]init];
//	data = self.array[indexPath.row];
//	traveVC.detail.code = data.code;
	if (nil != traveVC.detail) {
		[self.navigationController pushViewController:traveVC animated:YES];

	}
}



- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	if (nil == self.address ) {
		return self.address;
	}
	return @"定位中";

}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - gps and adress

- (void)beginLBS
{
	
	locationManager = [[CLLocationManager alloc] init]; //初始化本地位置的类实例
	geocoder = [[CLGeocoder alloc] init]; //打开经纬度与地理位置的转换
	locationManager.delegate = self; //设置委托
	locationManager.desiredAccuracy = kCLLocationAccuracyBest; //设置精确度最好
	
	[locationManager startUpdatingLocation];//更新
	

	
}

- (void)AlertController:(NSString *)error
{
	UIAlertView * alert = [[UIAlertView alloc]  initWithTitle:@"定位错误" message:error delegate:self cancelButtonTitle:@"取消" otherButtonTitles: nil];
	
	[alert show];
	
}

//出现错误的时候
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
	NSLog(@"定位: %@", error);
	
	if(error.code == kCLErrorLocationUnknown){
		NSLog(@"当前无法获取到位置信息");

		[self AlertController:@"当前无法获取到位置信息。"];
		
	} else if (error.code == kCLErrorNetwork) {
		NSLog(@"网络异常 - 无法获取到位置信息。");
		
		[self AlertController:@"网络异常 - 无法获取到位置信息。"];
	} else if (error.code == kCLErrorDenied) {
		NSLog(@"您的移动设备禁用了获取位置的服务。");
		
		[self AlertController:@"您的移动设备禁用了获取位置的服务。"];
		[locationManager stopUpdatingLocation];
	}
	UIAlertView *errorAlert = [[UIAlertView alloc]
							   initWithTitle:@"错误提醒"
							   message:@"获取位置信息失败！"
							   delegate:nil
							   cancelButtonTitle:@"OK"
							   otherButtonTitles:nil];
	[errorAlert show];
}

//更新位置，以及经纬度数据与详细地理位置进行转换
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
	NSLog(@"didUpdateToLocation: %@", newLocation);
	CLLocation *currentLocation = newLocation;
	
	if(currentLocation != nil){
		self.longitude = [NSString stringWithFormat:@"%.11f", currentLocation.coordinate.latitude];
		self.latitude = [NSString stringWithFormat:@"%.11f", currentLocation.coordinate.longitude];
	}
	
	// 停止location manager
	[locationManager stopUpdatingLocation];
	
//	NSLog(@"#############");
//	
//	NSLog(@"%@",self.longitude);
//	NSLog(@"%@",self.latitude);
//	
//	NSLog(@"#############");
	
	 // 转换地址
	/*
		[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
	 
	 if(error == nil && [placemarks count]>0){
	 placemark = [placemarks lastObject];
	 self.address = [NSString stringWithFormat:@"%@ %@\n%@\n%@",
	 placemark.country,
	 placemark.locality,
	 placemark.subLocality,
	 placemark.description];
	 NSLog(@"%@",self.address);
	 
	 
	 } else {
	 self.address = @"地址没有找到！";
	 }
		}];
	 */
	
	
	GoogleToBaidu *xy = [GoogleToBaidu GoogleToBaiduLongitude:[self.longitude floatValue] latitude:[self.latitude floatValue]];
	

	static dispatch_once_t onceToken;
	dispatch_once(&onceToken, ^{
		NSLog(@"只执行一次");
		
		
		// 转换地址
		
		[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
			
			if(error == nil && [placemarks count]>0){
				placemark = [placemarks lastObject];
				self.address = [NSString stringWithFormat:@"%@ %@\n%@\n%@",
								placemark.country,
								placemark.locality,
								placemark.subLocality,
								placemark.description];
				NSLog(@"%@",self.address);
				
				
			} else {
				self.address = @"地址没有找到！";
			}
		}];

		
		NSLog(@"longitude  %f",xy.x);
		NSLog(@"latitude  %f",xy.y);
		
		[self loadData:xy];
		
	});
	
	
	
}

- (void)loadData:(GoogleToBaidu *)lines
{
	
		NSString *startpos = [NSString stringWithFormat:@"%d",0];//向数据请求的数据列表开始位置
		NSString *eachpage = [NSString stringWithFormat:@"%d",20];//每次请求的数据个数
		
		
		NSString *urlstr = [NSString stringWithFormat:@"http://mobileapp.roadqu.com/api/mobile/qunawan/poi/search?startpos=%@&radius=200000&lng=%f&pageflag=nearby&token=5444cecc0c750&lat=%f&eachpage=%@&a_t=1413813767231&sign=d3787ea8fbec690f3aedd077f37c01488a7a9c9d", startpos,lines.x,lines.y,eachpage];
		
		NSLog(@"[LBSTableViewController]^^^^^^^^^^^^^DataURL:%@",urlstr);
	
	
	
		AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
		[manager GET:urlstr parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
			
			NSArray *array1 = [responseObject valueForKey:@"data"];
			NSLog(@"[LBSTableViewController]  Data down");
			//NSLog(@"%@",dic1);

			_array = [[NSMutableArray alloc] initWithCapacity:[array1 count]];
			for (NSDictionary *dic2 in array1) {
				NearbyData *model = [[NearbyData alloc] init];
				
				[model setValuesForKeysWithDictionary:dic2];
				[self.array addObject:model];
			
				NSLog(@"%@",model.avatar);

				
				model = nil;
				[self.tableView reloadData];
			}
			
			NSLog(@"[LBSTableViewController]  Data  OK");

		} failure:^(NSURLSessionDataTask *task, NSError *error) {
	
//			UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"error" message:@"error" preferredStyle:(UIAlertControllerStyleAlert)];
	
		}];
	

}





@end
